<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="企业名称" prop="corpName">
              <el-input v-model="queryParams.corpName" placeholder="请输入企业名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAuth" v-hasPermi="['bus:jqtCpHtInfo:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="jqtCpHtInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="唯一ID" align="center" prop="id" v-if="false" />
        <el-table-column label="企业名称" align="center" prop="corpName" />
        <el-table-column label="企业ID" align="center" prop="corpId" show-overflow-tooltip/>
        <el-table-column label="应用ID" align="center" prop="suiteId" show-overflow-tooltip/>
        <el-table-column label="授权时间" prop="createTime" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="editRemarkData(scope.row)" v-hasPermi="['bus:jqtCpHtInfo:edit']">备注</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['bus:jqtCpHtInfo:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改企业互通信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <div id="content_1" style="display: block;">
        <div class="m-info-item">
          <label>操作提醒:</label>
          <div class="text">
            点击下方按钮安装 <img src="https://wework.qpic.cn/wwpic3az/869727_mJ-e-kmmQQ2r_am_1750173653/0" style="height: 25px;margin: 0 5px;"> ，并将功能授权给应用。
          </div>
        </div>
        <div class="m-info-item">
          <label>绑定说明:</label>
          <div class="text">仅帮助您管理获客助手以及企业客户信息；请放下使用。
          </div>
        </div>
        <div class="m-info-item m-mt-1" v-if="authUrl">
          <a :href="authUrl" @click="cancel" class="m-btn m-btn-primary">点击安装企业微信应用</a>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="JqtCpHtInfo" lang="ts">
import {
  listJqtCpHtInfo,
  getJqtCpHtInfo,
  delJqtCpHtInfo,
  addJqtCpHtInfo,
  updateJqtCpHtInfo,
  getAuthUrl, authCpCallback, editRemark
} from '@/api/bus/jqtCpHtInfo';
import { JqtCpHtInfoVO, JqtCpHtInfoQuery, JqtCpHtInfoForm } from '@/api/bus/jqtCpHtInfo/types';
import { getBaseUrl } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));


const jqtCpHtInfoList = ref<JqtCpHtInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const jqtCpHtInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: JqtCpHtInfoForm = {
  id: undefined,
  remark: undefined,
  userId: undefined,
  suiteId: undefined,
  corpId: undefined,
  corpName: undefined,
  corpFullName: undefined,
  authUserId: undefined,
  authOpenUserid: undefined,
  authName: undefined,
  authAvatar: undefined,
  permanentCode: undefined,
  subjectType: undefined,
  corpWxqrcode: undefined,
  verifiedEndTime: undefined,
  status: undefined
}
const data = reactive<PageData<JqtCpHtInfoForm, JqtCpHtInfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    suiteId: undefined,
    corpId: undefined,
    corpName: undefined,
    corpFullName: undefined,
    authUserId: undefined,
    authOpenUserid: undefined,
    authName: undefined,
    authAvatar: undefined,
    permanentCode: undefined,
    subjectType: undefined,
    corpWxqrcode: undefined,
    verifiedEndTime: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询企业互通信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listJqtCpHtInfo(queryParams.value);
  jqtCpHtInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  authUrl.value = '';
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  jqtCpHtInfoFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: JqtCpHtInfoVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
const authUrl = ref<string>('');
/** 新增授权按钮 */
const handleAuth = async() => {
  reset();
  const data = await getAuthUrl(getBaseUrl());
  if(data.code !== 200){
    proxy?.$modal.msgError(data.msg);
    return;
  }
  dialog.visible = true;
  dialog.title = "添加企业互通信息";
  authUrl.value = data.data;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: JqtCpHtInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getJqtCpHtInfo(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改企业互通信息";
}

/** 提交按钮 */
const submitForm = () => {
  jqtCpHtInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateJqtCpHtInfo(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addJqtCpHtInfo(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: JqtCpHtInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除企业互通信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delJqtCpHtInfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 编辑备注 */
const editRemarkData = async (row?: JqtCpHtInfoVO) => {
  const _ids = row?.id || ids.value;
  ElMessageBox.prompt('修改企业互通备注', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
    .then(async ({ value }) => {
      await editRemark({
        id: row?.id,
        remark: value
      });
      proxy?.$modal.msgSuccess("编辑成功");
      row.remark = value;
    })
    .catch(() => {
    })
}

onMounted(() => {
  authCpCallbackData();
  getList();
});
/** 授权企业信息 */
const authCpCallbackData = async() => {
  const route = useRoute();
  const router = useRouter();
  // 获取查询参数
  const authCode = route.query.auth_code;
  const state = route.query.state;
  const expiresIn = route.query.expires_in;
  if(authCode && expiresIn && state){
    console.log(authCode, state,expiresIn);
    // 移除查询参数，保留当前路径
    router.replace({
      path: route.path,
      query: {} // 清空查询参数
    });
    const res = await authCpCallback(authCode, state, expiresIn);
    if(res.code === 200){
      proxy?.$modal.msgSuccess("授权成功");
      await getList();
    }else{
      proxy?.$modal.msgError(res.msg);
    }
  }
}
</script>
<style>
.m-info-item {
  width: 100%;
  display: flex
;
  align-items: center;
  flex-direction: row;
  color: #7D7E7E;
  align-items: flex-start;
  font-size: 14px;
}
.m-info-item label {
  height: 32px;
  line-height: 32px;
  margin-right: 5px;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 0;
  color: #000000;
  white-space: nowrap;
}
.m-info-item .text {
  flex: 1;
  height: auto;
  line-height: 32px;
  float: left;
}
.m-mt-1 {
  margin-top: 15px;
}
.m-btn-primary {
  color: #fff !important;
  background-color: #556ee6 !important;
  border-color: #556ee6 !important;
}
.m-btn {
  width: auto;
  height: 40px;
  line-height: 40px;
  display: flex;
  align-items: center;
  color: #FFFFFF;
  padding: 0 15px;
  text-decoration: none;
  font-weight: 400;
  outline: none;
  border: none;
  margin-bottom: 15px;
  white-space: nowrap;
  cursor: pointer;
}
</style>
